/*
    用法：在油猴扩展中，选择新添加脚本，把所有代码复制到编辑框中就好，最后保存。添加完后，可以打开本目录下的闹钟src\pages\main.html页面即可。

    注意1：注意自己的src\pages\main.html页面文件所在的位置，修改下面代码中 @include 成对应的位置。

    注意2：如果 src\pages\main.html 页面是本地文件，要设置油猴的一些配置，不然油猴默认是忽略 file:/// 本地文件的：打开浏览器的扩展，选择【油猴】扩展-->打开【详细信息】-->勾选【允许访问文件 URL】
*/

// ==UserScript==
// @name         hifini获取
// @namespace
// @version      0.1
// @description  在https://hifini.com/网站获取音乐地址
// @author       You
// @icon         https://hifini.com/view/img/logo.png
// @icon         C:\weijun.wu\learning_code\JavaScript\favicon.ico
// @include      file:///D:/code/learning_code/_%E9%A1%B9%E7%9B%AE/%E9%97%B9%E9%92%9F/*
// @include      https://hifini.com/*
// @require      https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function () {
  // 'use strict';
  let myObj = {
      // 搜搜和获取首页歌曲
      getMusic: function (url__) {
          let than = this;
          GM_xmlhttpRequest({
              method: "get",
              url: url__ || 'https://hifini.com/forum-1.htm',
              headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
              },
              onload: function (res) {
                  if (res.status === 200) {
                      // console.log(res.responseText)
                      let data = res.responseText;
                      var reg = /<a.*?href="(.*?)".*?>.*?《.*?》.*?a>/g;
                      var resres = data.match(reg);
                      let musicMain = [];
                      if (!resres || resres.length == 0) {
                          alert("找不到歌曲！！！")
                          return
                      };
                      resres.forEach(element => {
                          musicMain.push("https://hifini.com/" + /\<a.*?href=\"(.*?)\".*?《(.*)》.*?\<\/a\>/.exec(element)[1])
                      });
                      // console.log('', musicMain)
                      than.getUrl(musicMain)
                  } else {
                      console.log(res)
                  }
              },
              onerror: function (err) {
                  console.log(err)
              }
          });
      },
      // 获取歌曲信息
      getUrl(musicMain) {
          let nn = 0;
          let than = this;
          than.musicUrl = []
          for (let index = 0; index < musicMain.length; index++) {
              const element = musicMain[index];
              GM_xmlhttpRequest({
                  method: "get",
                  url: element,
                  headers: {
                      "Content-Type": "application/x-www-form-urlencoded"
                  },
                  onload: function (res) {
                      if (res.status === 200) {
                          let data = res.responseText;
                          nn += 1;
                          try {
                              // 获取歌词
                              let zz = /<h5>\s*?歌词\s*?<\/h5>(.*?)<h5>/gims.exec(data)
                              zz = zz[1].replace(/<p>|<\/p>|<\/p>\s*?<p>/gims, ' ').trim()
                              zz = zz.replace(/\s+/g, ' ')
                              let gc = []
                              zz.split(' ').forEach((item, index) => {
                                  gc.push(item.trim());
                              })

                              // 获取歌曲信息
                              than.musicUrl.push({
                                  name: /title.*?\'(.*?)\',/g.exec(data)[1],
                                  artist: /author.*?\'(.*?)\',/g.exec(data)[1],
                                  url: "https://hifini.com/" + /url.*?\'(.*?)\'/g.exec(data)[1] + /generateParam\(\'(.*?)\'\),/g.exec(data)[1],
                                  cover: /pic.*?\'(.*?)\'/g.exec(data)[1],
                                  lyric: gc, // 歌词
                              })
                          } catch (e) { }
                          if (musicMain.length == nn) {
                              console.log('', than.musicUrl);
                              window.unsafeWindow.addList()
                          }
                      } else {
                          console.log(res)
                          window.unsafeWindow.addList()
                      }
                  },
                  onerror: function (err) {
                      console.log(err)
                      window.unsafeWindow.addList()
                  }
              });
          }
      },
      musicUrl: [],   // 保存所有的歌曲地址
      /* 获取句子鸡汤 */
      getSentenceChickenSoup(fn) {
          let than = this
          GM_xmlhttpRequest({
              method: "get",
              url: 'http://juzi.oulu.me/api.php',
              headers: {
                  // "Content-Type": "application/x-www-form-urlencoded"
              },
              onload: function (res) {
                  if (res.status === 200) {
                      let data = res.responseText.split('"')[1];
                      // console.log(data)
                      fn && fn(data)
                  } else {
                      console.log(res)
                  }
              },
              onerror: function (err) {
                  console.log(err)
                  fn && fn('')
              }
          });
      }
  }
  // 获取歌曲信息需要的验证代码
  function base32Encode(str) {
      var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
      var bits = "";
      var base32 = "";

      for(var i = 0; i < str.length; i++) {
          var bit = str.charCodeAt(i).toString(2);
          while(bit.length < 8) {
              bit = "0" + bit;
          }
          bits += bit;
      }

      while(bits.length % 5 !== 0) {
          bits += "0";
      }

      for(var j = 0; j < bits.length; j += 5) {
          var chunk = bits.substring(j, j+5);
          base32 += base32chars[parseInt(chunk, 2)];
      }

      while(base32.length % 8 !== 0) {
          base32 += "=";
      }

      return base32.replace(/=/g, 'HiFiNiYINYUECICHANG');
  }
  // 获取歌曲信息需要的验证代码
  function generateParam(data) {
      var key = '95wwwHiFiNicom27';
      var outText = '';

      for(var i = 0, j = 0; i < data.length; i++, j++) {
          if(j == key.length) j = 0;
          outText += String.fromCharCode(data.charCodeAt(i) ^ key.charCodeAt(j));
      }
      return base32Encode(outText);
  }
  Object.assign(window, myObj);
  window.unsafeWindow.myWindow = window
  // Your code here...
})();